<?php

namespace App\Admin\Metrics\Examples;

use Dcat\Admin\Widgets\Metrics\Line;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Models\CustomerInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class NewCustomers extends Line
{
    /**
     * 初始化卡片内容
     *
     * @return void
     */
    protected function init()
    {
        parent::init();

        $this->title('留资新增');
        $this->dropdown([
            '7' => '最近七天',
            '30' => '最近30天',
        ]);
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        $option = $request->get('option') ?? 7;
        $option -= 1;
        $start = Carbon::now()->subDays($option)->toDateString();
        $cache_key = 'total-customer-infos:' . $option . ':' . $start;
        $total = Cache::remember($cache_key, 86400, function () use ($start) {
            return CustomerInfo::whereDate('created_at', '>', $start)->count();
        });

        $cache_key_2 = 'new-customer-infos:' . $option . ':' . $start;
        $data = Cache::remember($cache_key_2, 86400, function () use ($start, $option) {
            $arr = CustomerInfo::select(DB::raw('count(*) as customerInfo_count, date(`created_at`) as created_date'))->where('created_at', '>', $start)->groupByRaw('date(`created_at`)')->get()->toArray();
            $arr2 = array_combine(array_column($arr, 'created_date'), array_column($arr, 'customerInfo_count'));
            $data = [];
            for ($i = $option; $i >= 0; $i--) {
                $day = Carbon::now()->subDays($i)->toDateString();
                $data[] = isset($arr2[$day]) ? $arr2[$day] : 0;
            }
            return $data;
        });

        // 卡片内容
        $this->withContent($total);
        // 图表数据
        $this->withChart($data);

    }

    /**
     * 设置图表数据.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        return $this->chart([
            'series' => [
                [
                    'name' => $this->title,
                    'data' => $data,
                ],
            ],
        ]);
    }

    /**
     * 设置卡片内容.
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent($content)
    {
        return $this->content(
            <<<HTML
<div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
    <h2 class="ml-1 font-lg-1">{$content}</h2>
    <span class="mb-0 mr-1 text-80">{$this->title}</span>
</div>
HTML
        );
    }
}
